import pymssql

import os

class DBConnect:

    _DB_INSTANCE = None

    _SERVER = os.environ.get('DB_URL')
    _USER = os.environ.get('DB_USER')
    _PASS = os.environ.get('DB_PA')
    _PORT = int(os.environ.get('DB_PORT'))
    _DBNAME = os.environ.get('DB_DB')
    _CHATCODE = 'utf8'

    def __init__(self):
        if self._DB_INSTANCE is None:
            self._DB_INSTANCE = pymssql.connect(host=self._SERVER,user=self._USER,password=self._PASS,port=self._PORT,
                                                database=self._DBNAME,charset=self._CHATCODE)

    def query(self, sql):
        cursor = self._DB_INSTANCE.cursor()
        cursor.execute(sql)
        datas = []
        while True:
            row = cursor.fetchone()
            if row is None:
                break
            datas.append(row)
        cursor.close()
        return datas

    def closeDb(self):
        self._DB_INSTANCE.close()